package com.example.service;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

public class PersonProvider extends ContentProvider {

	private DbOpenHelper dbOpenHelper;
	private final static UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
	static{
		uriMatcher.addURI("cn.license.providers.personProvider", "person", 1);
		uriMatcher.addURI("cn.license.providers.personProvider", "person/#", 2);
	}
	@Override
	public boolean onCreate() {
		dbOpenHelper = new DbOpenHelper(this.getContext(),"asisoft",null,1);
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
		switch(uriMatcher.match(uri)){
		case 1:
			db.query("person", projection, selection, selectionArgs, null, null, sortOrder);
		case 2:
			return null;
		}
		return null;
	}

	@Override
	public String getType(Uri uri) {
		switch(uriMatcher.match(uri)){
		case 1:
			return "vnd.android.cursor.dir/";
		case 2:
			return "vnd.android.cursor.item";
		}
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		//dbOpenHelper = new DbOpenHelper(this.getContext(),"asisoft",null,1);
		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
		switch(uriMatcher.match(uri)){
		case 1:
			Long rowId = db.insert("person", null, values);
			Uri insertUri = Uri.withAppendedPath(uri, rowId.toString());
			return insertUri;
		case 2:
			return null;
		}
		return null;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
		switch(uriMatcher.match(uri)){
		case 1:
			return db.delete("person", selection, selectionArgs);
		case 2:
			Long rowId = ContentUris.parseId(uri);
			String where = "id="+rowId;
			if(selection!=null && "".equals(selection.trim()))
				where+=" and "+selection;
			return db.delete("person", where, selectionArgs);
		}
		return 0;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
		switch(uriMatcher.match(uri)){
		case 1:
			return db.update("person", values, selection, selectionArgs);
		case 2:
			Long rowId = ContentUris.parseId(uri);
			String where = "id="+rowId;
			if(selection!=null && "".equals(selection.trim()))
				where+=" and "+selection;
			return db.update("person", values, where, selectionArgs);
		}
		return 0;
	}

}
